﻿using System;
using System.Collections.Generic;
using System.Web.UI;


namespace AutoCompleteTextBox
{
    public class AutoCompleteTextBox : ScriptControl
    {
        private string SourceID { get; set; }

        public string DataSourceId { get; set; }

        private AutocompleteDataSource AutoCompleteDataSource { get; set; }

        public static string YUIPath { get; set; }

        static AutoCompleteTextBox()
        {
            YUIPath = ControlHelper.DefaultYUIPath;
        }

        protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            var control = new ScriptControlDescriptor("AutoCompleteTextBox.AutoCompleteTextBox", this.ClientID);
            control.AddProperty("SourceID", SourceID);
            yield return control;
        }

        protected override IEnumerable<ScriptReference> GetScriptReferences()
        {
            return new ScriptReference[]
            {
                 new AutoCompleteTextBoxScript()
            };
        }

        protected override void OnPreRender(EventArgs e)
        {
            YUIPathManager.YUIPathEditor();
            AutoCompleteTextBoxDataSourceManager dataSourceManager = new AutoCompleteTextBoxDataSourceManager(AutoCompleteDataSource, this, DataSourceId, YUIPath);
            SourceID = dataSourceManager.SourceID;
            base.OnPreRender(e);
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }
    }
}
